﻿using MediatR;
using PublicCommon;
using T_vehicle.Domain;
using T_vehicle.Infrastructure.Interfacec;
using T_vehicle.Read.API.Application.Command.IllegalCommand;

namespace T_vehicle.Read.API.Application.CommandHandlers.IllegalCommandHandlers
{
    public class GetIllgalCommandHandlers:IRequestHandler<GetIllgalCommand,PageResult<Illegal>>
    {
        private readonly IIllegalRepository illegalRepository;

        public GetIllgalCommandHandlers(IIllegalRepository illegalRepository)
        {
            this.illegalRepository = illegalRepository;
        }

        public async Task<PageResult<Illegal>> Handle(GetIllgalCommand request, CancellationToken cancellationToken)
        {
           var list =  illegalRepository.GetAllAsync().Result.Where(x=>x.IsDel==false).AsQueryable();
            if (!string.IsNullOrEmpty(request.LicenNumber))
            {
                list = list.Where(x => x.LicenNumber.Contains(request.LicenNumber));
            }
            if (!string.IsNullOrEmpty(request.IllegalTitle))
            {
                list = list.Where(x => x.IllegalTitle.Contains(request.IllegalTitle));
            }
            if (!string.IsNullOrEmpty(Convert.ToString(request.ViolatorsDate)))
            {
                list = list.Where(x => Convert.ToString(x.ViolatorsDate) == Convert.ToString(request.ViolatorsDate));
            }
            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling((totalCount * 1.0) / request.pageSize);
            var res = list.Skip(request.pageIndex - 1 * request.pageSize).Take(request.pageSize).ToList();
            return  new PageResult<Illegal>
            {
                TotalCount = totalCount,
                PageCount = pageCount,
                List = res
            };
        }
    }
}
